package com.epam.facebook_client.services;

import java.util.ArrayList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicInteger;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.util.SparseArray;

public class ServiceHelper {

	public static final String SERVICE_NAME = "SERVICE_HELPER";

	private ArrayList<ServiceCallbackListener> currentListeners = new ArrayList<ServiceCallbackListener>();
	private AtomicInteger idCounter;
	private SparseArray<Intent> pendingActivities;

	private Context context;

	public static ServiceHelper get(Context context) {
		return (ServiceHelper) context.getApplicationContext().getSystemService(SERVICE_NAME);
	}

	public ServiceHelper(Context context) {
		this.context = context.getApplicationContext();
		idCounter = new AtomicInteger();
		pendingActivities = new SparseArray<Intent>();
	}

	public void addListener(ServiceCallbackListener listener) {
		currentListeners.add(listener);
	}

	public void removeListener(ServiceCallbackListener listener) {
		currentListeners.remove(listener);
	}

	private int createId() {
		return idCounter.getAndIncrement();
	}

	public int startService(String action, Map<String, String> parameter) {
		int requestId = createId();
		Intent i = createIntent(action, requestId);
		if (parameter != null) {
			for (Entry<String, String> entry : parameter.entrySet()) {
				i.putExtra(entry.getKey(), entry.getValue());
			}
		}
		pendingActivities.append(requestId, i);
		context.startService(i);
		return requestId;
	}

	public boolean isPending(int requestId) {
		return pendingActivities.get(requestId) != null;
	}

	private Intent createIntent(String action, final int requestId) {
		Intent i = new Intent(context, RESTService.class);
		i.setAction(action);
		i.putExtra(RESTService.EXTRA_STATUS_RECEIVER, new ResultReceiver(new Handler()) {
			@Override
			protected void onReceiveResult(int resultCode, Bundle resultData) {
				super.onReceiveResult(resultCode, resultData);
				Intent requestIntent = pendingActivities.get(requestId);
				if (isPending(requestId)) {
					pendingActivities.remove(requestId);
					for (int j = 0; j < currentListeners.size(); j++) {
						currentListeners.get(j).onServiceResult(requestId, requestIntent, resultCode, resultData);
					}
				}
			}
		});
		return i;
	}
}
